﻿using System;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Home.MobileSales.Common.Components
{
    public partial class OpenFileDialogEx : Form
    {
        private string filter = "*";
        private string selectedFileName = string.Empty;
        private string currentDirectory = "\\";
        private bool changingDir = false;
        private bool onlyDir = false;
        private enum FileIcon : int
        {
            File,
            Directory,
            StorageCard,
            Up
        }

        public string SelectedFileName
        {
            get { return selectedFileName; }
        }

        public string SelectedPath
        {
            get { return currentDirectory; }
        }

        public string SelectedFullName
        {
            get{ return Path.Combine(currentDirectory, selectedFileName); }
        }

        public void ShowDirectory (string directoryPath)
        {
            changingDir = true;
            managerListView.SuspendLayout();
            managerListView.Items.Clear();
            currentDirectory = directoryPath;
            if (currentDirectory != Directory.GetDirectoryRoot(currentDirectory))
            {
                ListViewItem itm = new ListViewItem("..");
                itm.Tag = new DirectoryInfo(currentDirectory).Parent.FullName;
                itm.ImageIndex = (int)FileIcon.Up;
                managerListView.Items.Add(itm);
            }

            string[] directories = Directory.GetDirectories(currentDirectory);
            Array.Sort(directories, (item1, item2) => String.Compare(Path.GetFileName(item1.ToString()), Path.GetFileName(item2.ToString()), true, CultureInfo.InvariantCulture));
            foreach (string dir in directories)
            {
                ListViewItem itm = new ListViewItem(Path.GetFileName(dir));
                itm.Tag = dir;
                FileInfo info = new FileInfo(dir);
                if ((info.Attributes & (FileAttributes.Directory | FileAttributes.Temporary)) == (FileAttributes.Directory | FileAttributes.Temporary))
                {
                    itm.ImageIndex = (int)FileIcon.StorageCard;
                }
                else
                {
                    itm.ImageIndex = (int)FileIcon.Directory;
                }
                managerListView.Items.Add(itm);
            }
            if (!onlyDir)
            {
                string[] files = Directory.GetFiles(currentDirectory, filter);
                Array.Sort(files, (item1, item2) => String.Compare(Path.GetFileName(item1.ToString()),
                                                                   Path.GetFileName(item2.ToString()), true,
                                                                   CultureInfo.InvariantCulture));
                foreach (string file in files)
                {
                    ListViewItem itm = new ListViewItem(Path.GetFileName(file));
                    itm.Tag = file;
                    itm.ImageIndex = (int) FileIcon.File;
                    managerListView.Items.Add(itm);
                }
            }
            managerListView.ResumeLayout();
            selectedFileTextBox.Text = string.Empty;
            UpdatePathComboBox();
            changingDir = false;
        }

        private void UpdatePathComboBox()
        {
            changeDirComboBox.BeginUpdate();
            changeDirComboBox.Items.Clear();
            string rootPath = Path.GetPathRoot(currentDirectory);
            List<string> directories = new List<string>();
            directories.Add(rootPath);
            if (currentDirectory != rootPath)
            {
                string[] parts = currentDirectory.Substring(1).Split(Path.DirectorySeparatorChar); 
                directories.Add(rootPath + parts[0]);
                if (parts.Length > 1)
                {
                    for (int i = parts.Length - 1; i > 0; i--)
                    {
                        directories.Add(rootPath + String.Join(Path.DirectorySeparatorChar.ToString(), parts, 0, i + 1));
                    }
                }
            }
            directories.Sort();
            foreach (string dir in directories)
            {
                changeDirComboBox.Items.Add(dir);
            }
            changeDirComboBox.SelectedIndex = changeDirComboBox.Items.Count - 1;
            changeDirComboBox.EndUpdate();
        } 

        public OpenFileDialogEx()
        {
            InitializeComponent();
            this.filter = "*.*";
            currentDirectory = "\\";
            onlyDir = false;
            ShowDirectory(currentDirectory);
        }

        public OpenFileDialogEx(string currentPath): this() 
        {
            currentDirectory = currentPath;
            ShowDirectory(currentDirectory);
        }

        public OpenFileDialogEx (string currentPath, bool onlyDirectory):this(currentPath)
        {
            onlyDir = onlyDirectory;
            ShowDirectory(currentDirectory);
        }

        public OpenFileDialogEx (string currentPath, string f, bool onlyDirectory ):this(currentPath, onlyDirectory)
        {
            this.filter = f;
            ShowDirectory(currentDirectory);
        }

        private void managerListView_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (managerListView.SelectedIndices.Count > 0 && (managerListView.Items[managerListView.SelectedIndices[0]].ImageIndex != (int)FileIcon.Up))
            {
                okMenuItem.Enabled = true;
                selectedFileTextBox.Text = managerListView.Items[managerListView.SelectedIndices[0]].Text;
            }
            else
            {
                okMenuItem.Enabled = false;
            }
        }

        private void managerListView_ItemActivate(object sender, EventArgs e)
        {
            ListViewItem selectedItem = managerListView.Items[managerListView.SelectedIndices[0]];
            if (selectedItem != null) 
            {
                switch(selectedItem.ImageIndex) 
                {
                    case (int)FileIcon.File:
                        selectedFileName = selectedFileTextBox.Text;
                        DialogResult = DialogResult.OK;
                        break;
                    case (int)FileIcon.Directory:
                    case (int)FileIcon.StorageCard:
                    case (int)FileIcon.Up:
                        ShowDirectory(selectedItem.Tag.ToString());
                        break;
                }
            }
        
        }

        private void changeDirComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!changingDir && changeDirComboBox.SelectedItem != null)
                ShowDirectory(changeDirComboBox.SelectedItem.ToString());
        }

        private void okMenuItem_Click(object sender, EventArgs e)
        {
            if (onlyDir)
            {
                selectedFileName = selectedFileTextBox.Text;
                DialogResult = DialogResult.OK;
            }
            else
            {
                managerListView_ItemActivate(null, null);
            }
        }

        private void cancelMenuItem_Click(object sender, EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
        }
    }
}